﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using YunLuPos.DB.Service;
using YunLuPos.Entity;
using YunLuPos.Entity.Constant;
using YunLuPos.Payment;
using YunLuPos.Printer;
using YunLuPos.Utils;

namespace YunLuPos.SellView
{
    public partial class OrderSelectForm : UIForm
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SaleOrderAccountService));
        public SaleOrder selectedOrder = null;
        SaleOrderService orderService = new SaleOrderService();
        SaleOrderGoodsService orderGoodsService = new SaleOrderGoodsService();
        SaleOrderAccountService accountService = new SaleOrderAccountService();
        public OrderSelectForm()
        {
            InitializeComponent();
        }

        private void OrderSelectForm_Load(object sender, EventArgs e)
        {
            this.rejectBtn.Style = UIStyle.Red;
            this.uiButton4.Style = UIStyle.Red;
            this.orderGrid.AutoGenerateColumns = false;
            this.goodsGrid.AutoGenerateColumns = false;
            this.accountGrid.AutoGenerateColumns = false;
            try
            {
                int w = Int32.Parse(StaticInfoHoder.Width);
                int h = Int32.Parse(StaticInfoHoder.Height);
                this.Width = w;
                this.Height = h;
                this.ShowTitle = (StaticInfoHoder.ShowTop == "1");
                if (StaticInfoHoder.FullScreen == "1")
                {
                    this.WindowState = FormWindowState.Maximized;
                }
                else
                {
                    this.WindowState = FormWindowState.Normal;
                }
            }
            catch
            {

            }
            loadOrder();

        }

        void loadOrder()
        {
            String owner = InIUtil.ReadInIData(InIUtil.GenSection, InIUtil.G_ORDER_OWNER, "1");
            string saleDate = DateTime.Now.ToString("yyyy-MM-dd");
            List<SaleOrder> orders = null;
            if ("1".Equals(owner))
            {
                orders = orderService.listDayOrder(saleDate, null);
            }else
            {
                orders = orderService.listDayOrder(saleDate, StaticInfoHoder.commInfo.cashierCode);
            }
            if(orders != null)
            {
                Double payAmount = 0;
                Double goodsCount = 0;
                Int32 orderCount = orders.Count();
                foreach(SaleOrder order in orders)
                {
                    if (SaleOrderType.REJECT.ToString().Equals(order.orderType))
                    {
                        order.realAmount = -1 * order.realAmount;
                        order.payAmount = -1 * order.payAmount;
                        order.goodsCount = -1 * order.goodsCount;
                        order.dotAmount = -1 * order.dotAmount;
                        order.disAmount = -1 * order.disAmount;
                    }
                    payAmount = order.payAmount + payAmount;
                    goodsCount = order.goodsCount + goodsCount;
                }
                this.totalAmount.Text = payAmount.ToString("F2");
                this.totalCount.Text = goodsCount.ToString("F3");
                this.orderCount.Text = orderCount + "";
                this.orderGrid.DataSource = orders;
            }
        }

        private void orderGrid_CurrentCellChanged(object sender, EventArgs e)
        {
            if (orderGrid.CurrentRow != null)
            {
                SaleOrder order = orderGrid.CurrentRow.DataBoundItem as SaleOrder;
                if (!order.orderCode.Equals(this.selectedOrder))
                {
                    this.selectedOrder = orderService.getFullOrder(order.orderCode);
                    this.goodsGrid.DataSource = selectedOrder.goods;
                    this.accountGrid.DataSource = selectedOrder.accounts;
                }
            }
        }

        private void OrderSelectForm_KeyDown(object sender, KeyEventArgs e)
        {
            Console.WriteLine("keydown");
            if (e.KeyCode == Keys.Up)
            {
                moveUp();
            }
            else if (e.KeyCode == Keys.Down)
            {
                moveDown();
            }
            else if (e.KeyCode == Keys.Enter)
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
            else if (e.KeyCode == Keys.F2)
            {
                //退货
                reject();
            }
            else if (e.KeyCode == Keys.F3)
            {
                //重打印
                rePrint();

            }else if(e.KeyCode == Keys.F4)
            {
                //联机退货
                onLineReject();
            }
        }
        /**
       * 下移选中行
       * 到最后一行停止
       * */
        public void moveUp()
        {
            Console.WriteLine(orderGrid.CurrentRow.Index);
            if (orderGrid.RowCount == 0)
            {
                return;
            }
            if (orderGrid.CurrentRow.Index > 0)
            {
                int moveRow = orderGrid.CurrentRow.Index;
                Console.WriteLine(moveRow);
                orderGrid.CurrentCell = orderGrid.Rows[moveRow].Cells[0];
            }
        }

        /**
        * 上一选中行
        * 到第一行停止
        * */
        public void moveDown()
        {
            if (orderGrid.RowCount == 0)
            {
                return;
            }
            if (orderGrid.CurrentRow.Index < orderGrid.RowCount - 1)
            {
                int moveRow = orderGrid.CurrentRow.Index;
                orderGrid.CurrentCell = orderGrid.Rows[moveRow].Cells[0];
            }
        }

        private void orderGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (orderGrid.Columns["disAmount"].Index == e.ColumnIndex)
            {
                if (e.Value == null)
                {
                    return;
                }
                e.Value = Double.Parse(e.Value.ToString()).ToString("F2");
            }
            if (orderGrid.Columns["payAmount"].Index == e.ColumnIndex)
            {
                if (e.Value == null)
                {
                    return;
                }
                e.Value = Double.Parse(e.Value.ToString()).ToString("F2");
            }
            if (orderGrid.Columns["realAmount"].Index == e.ColumnIndex)
            {
                if (e.Value == null)
                {
                    return;
                }
                e.Value = Double.Parse(e.Value.ToString()).ToString("F2");
            }
            if (orderGrid.Columns["state"].Index == e.ColumnIndex)
            {
                if (e.Value == null)
                {
                    return;
                }
                if (SaleOrderState.PAYED.ToString().Equals(e.Value))
                {
                    e.Value = "已支付";
                }
                if (SaleOrderState.SYNCED.ToString().Equals(e.Value))
                {
                    e.Value = "已上传";
                }
            }
            if (orderGrid.Columns["orderType"].Index == e.ColumnIndex)
            {
                if (e.Value == null)
                {
                    return;
                }
                if (SaleOrderType.SALE.ToString().Equals(e.Value))
                {
                    e.Value = "销售";
                }
                if(SaleOrderType.REJECT.ToString().Equals(e.Value))
                {
                    e.Value = "退货";
                }
            }
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            rePrint();
        }

        private void rejectBtn_Click(object sender, EventArgs e)
        {
            reject();
        }

        void onLineReject()
        {
            String orderNo = null;
            if (this.InputStringDialog(ref orderNo ,true,"请输入原销货单号"))
            {

            }
        }

        void reject()
        {
            Console.WriteLine("reject");
            if (selectedOrder == null)
            {
                return;
            }
            if(SaleOrderType.REJECT.ToString().Equals(selectedOrder.orderType))
            {
                return;
            }
            if (this.ShowAskDialog("执行退货将清空当前单据内容，确认将单据[" + selectedOrder.orderCode + "]退货?", this.Style))
            {
                SaleOrder order = orderService.createNewOrder(StaticInfoHoder.commInfo, true);
                DynamicInfoHoder.currentOrder = order;
                List<SaleOrderGoods> goods = selectedOrder.goods;
                foreach(SaleOrderGoods g in goods)
                {
                    Goods dto = new Goods();
                    dto.goodsCode = g.goodsCode;
                    dto.goodsName = g.goodsName;
                    dto.specs = g.specs;
                    dto.unitName = g.unit;
                    dto.barCode = g.barCode;
                    dto.unitCount = g.packCount;
                    dto.salePrice = g.disPrice;
                    orderGoodsService.addGoods(order, dto, g.goodsCount, g.disPrice,GoodsPriceSource.NORM, g.promCode);
                }
                if(selectedOrder.memberNo != null && selectedOrder.memberName != null)
                {
                    Member m = new Member();
                    m.mebCode = selectedOrder.memberNo;
                    m.mebName = selectedOrder.memberName;
                    orderService.setMemberInfo(order,m);
                }
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        void rePrint()
        {
            if(selectedOrder == null)
            {
                return;
            }
            if (this.ShowAskDialog("确认重打印单据[" + selectedOrder.orderCode + "]?",this.Style))
            {
                //打印订单
                List<string> list = orderService.PrintList(selectedOrder.orderCode);
                PrintBase pb = PrinterManager.getPrinter();
                if (pb != null)
                {
                    pb.initPrinter();
                    pb.open();
                    pb.writeLine(StaticInfoHoder.commInfo.cliqueName + "[" + StaticInfoHoder.commInfo.shopName + "]");
                    pb.writeLine("重打印单据");
                    pb.printList(list);
                    //打印签购单
                    List<String> keys = accountService.listMasterKeys(selectedOrder.orderCode);

                    if (keys != null)
                    {
                        foreach (String key in keys)
                        {
                            List<String> pList = PaymentManager.print(key);
                            if (pList != null && pList.Count > 0)
                            {
                                pb.printList(pList);
                            }
                        }
                    }
                    pb.NewRow();
                    pb.NewRow();
                    pb.NewRow();
                    pb.Dispose();
                    this.Close();
                }
            }
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            onLineReject();
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void goodsGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (goodsGrid.Columns["disAmount2"].Index == e.ColumnIndex)
            {
                if (e.Value == null)
                {
                    return;
                }
                e.Value = Double.Parse(e.Value.ToString()).ToString("F2");
            }
            if (goodsGrid.Columns["priceSource"].Index == e.ColumnIndex)
            {
                if (e.Value == null)
                {
                    return;
                }
                if (GoodsPriceSource.NORM.ToString().Equals(e.Value))
                {
                    e.Value = "正常";
                }
                if (GoodsPriceSource.VIP.ToString().Equals(e.Value))
                {
                    e.Value = "会员价";
                }
                if (GoodsPriceSource.POS.ToString().Equals(e.Value))
                {
                    e.Value = "POS变价";
                }
                if (GoodsPriceSource.BALANCE.ToString().Equals(e.Value))
                {
                    e.Value = "称台价";
                }
                if (GoodsPriceSource.PROM.ToString().Equals(e.Value))
                {
                    e.Value = "普通促销";
                }
                if (GoodsPriceSource.GROUP_PROM.ToString().Equals(e.Value))
                {
                    e.Value = "组合促销";
                }
            }
        }

        /// <summary>
        /// 清除历史单据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton4_Click(object sender, EventArgs e)
        {
            if (this.ShowAskDialog("确认清空所有本地单据？", this.Style))
            {
                try
                {
                    orderService.cleanAll();
                    this.ShowMessageDialog("清除数据成功", "成功", true, this.Style);
                }
                catch (Exception ex)
                {
                    logger.Error("清除数据错误", ex);

                }
            }


                
           
        }
    }
}
